package api

import (
	"common"
	"common/biz"
	"common/config"
	"common/jwts"
	"common/proto/api"
	"common/rpc"
	"context"
	"framework/msError"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"go.uber.org/zap"
	"net/http"
)

type UserHandler struct {
}

func NewUserHandler() *UserHandler {
	return &UserHandler{}
}

/*
*
必须是大写
*/
func (u *UserHandler) Register(ctx *gin.Context) {
	var request = api.RegisterParams{}
	if err := ctx.ShouldBindJSON(&request); err != nil {
		common.Fail(ctx, msError.NewError(http.StatusBadRequest, err)) //参数解析错误
		return
	}
	register, err := rpc.UserClient.Register(context.Background(), &api.RegisterParams{
		Account:       request.Account,
		LoginPlatform: 2,
	})
	if err != nil {
		common.Fail(ctx, msError.ToError(err)) //grpc的错误转成gin的
		return
	}
	uid := register.Uid
	zap.S().Infof("服务端注册,获取注册的uid:%s", uid)
	//生成jwt token
	claims := jwts.CustomClaims{
		Uid:              uid,
		RegisteredClaims: jwt.RegisteredClaims{},
	}
	token, err := jwts.GenToken(&claims, config.Conf.Jwt.Secret)
	if err != nil {
		zap.S().Errorf("register get token error:%v", err)
		common.Fail(ctx, biz.Fail)
		return
	}
	res := map[string]any{
		"token": token,
		"serverInfo": map[string]any{
			"host": config.Conf.Services["connector"].ClientHost,
			"port": config.Conf.Services["connector"].ClientPort,
		},
	}
	common.Success(ctx, res)
}
